import { createAction } from 'redux-actions'
import fetch from 'isomorphic-fetch'
import { check, Json, body, post, parseJSON, checkStatus, data, getJson, postJson, putJson } from './util'
import util from '../util'

export const login = createAction('login', (obj, cb) =>
	fetch('/auths/login', {
		...post,
		headers: Json,
		...body(obj)
	})
	.then(checkStatus)
	.then(parseJSON)
	.then(cb)
)

export const resetPassword = createAction('reset password', (password, cb) =>
	fetch('/auths/reset-password', {
		...postJson,
		...body({ password })
	})
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(res => {
			cb && cb()
			return res.data
		})
)

export 
const findPassword = createAction('find password', (email, cb) =>
  fetch('/auths/find-password/send-url', {
		...postJson,
		...body({ email })
	})
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(res => {
			cb && cb(res)
			return res.data
		})
)

export
const setPassword = createAction('set password', (password, cb) =>{
	
	let obj = (typeof password === "object") ? {...password} : {password};
	return fetch('/auths/find-password/reset', {
		...putJson,
		...body({ ...obj })
	})
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
})

export
const logout = createAction('logout', cb =>
  fetch('/auths/logout', getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const sendSms = createAction('send sms', (mobilePhone, cb) => 
  fetch(`/auths/sms-code/trusted-mobile-phones?mobilePhone=${mobilePhone}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const updateOnboardingAvatar = createAction('_', (arg, cb) => {
    arg = Object.keys(arg).map(key => `${key}=${arg[key]}`).join('&')
    return (
      fetch(`/onboarding-flows/org-account/avatar?${arg}`, getJson)
        .then(checkStatus)
        .then(parseJSON)
        .then(check)
        .then(res => cb(res.data))
    )
  }
)

export
const saveOrgAccount = createAction('_', (arg, cb) =>
  fetch('/onboarding-flows/org-account', {
		...postJson,
		...body(arg)
	})
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const initPassword = createAction('init password', (password, cb) =>
  fetch('/auths/init-password', {
		...postJson,
		...body({ password })
	})
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const initPasswordEmail = createAction('_', (emailAddress, cb) => 
  fetch(`/onboarding-flows/staff/init-pwd-email?${util.body({ emailAddress })}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(cb)
)

export
const verifyPassword = createAction('_', (password, cb) => 
  fetch('/auths/verify-password', {
    ...postJson,
    ...body({ password })
  })
    .then(checkStatus)
    .then(parseJSON)
    .then(check)
    .then(cb)
)


